import { 
  AdditiveBlending,
  AmbientLight,
  Color,
  Group,
  PerspectiveCamera, 
  Scene, 
  SpotLight, 
  Sprite, 
  SpriteMaterial, 
  TextureLoader, 
  Vector2, 
  WebGLRenderer
} from "three"
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'
import stats from "../utils/stats"
import dat from 'dat.gui'

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(-20, 12, 200)
camera.lookAt(0, 0, 0)

const renderer = new WebGLRenderer({ antialias: true })
renderer.setClearColor(0x000000)
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const ambient = new AmbientLight(0x0c0c0c)
scene.add(ambient)

const spotlight = new SpotLight(0xffffff)
spotlight.position.set(100, 100, 100)
scene.add(spotlight)
// scene.add(new SpotLightHelper(spotlight))

// 加载图片
function getTexture() {
  return new TextureLoader().load('/img/sprite-sheet.png')
}

let group :Group
const controls = {
  animate: true,
  size: 4,
  color: 0xffffff,
  transparents: true,
  opacity: 0.6,

  draw() {
    scene.remove(group)
    group = new Group()
    
    for (let i = 0; i < 500; i++) {
      group.add(createParticles(this.size, this.transparents, this.opacity, i % 5, this.color))
    }
    scene.add(group)
  }
}

controls.draw()

const gui = new dat.GUI()
gui.add(controls, 'animate')
gui.add(controls, 'transparents').onChange(e => controls.draw())
gui.add(controls, 'opacity', 0, 1).onChange(e => controls.draw())
// gui.addColor(controls, 'color')
gui.add(controls, 'size', 1, 10, 1).onChange(e => controls.draw())

const trackballControls = new TrackballControls(camera, renderer.domElement)

function render() {
  stats.update()
  trackballControls.update()

  if (controls.animate) {
    group.rotation.x += 0.01
    group.rotation.z += 0.01
  }

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}
render()


function createParticles(
  size: number, 
  transparent: boolean, 
  opacity: number, 
  spriteNumber: number,
  color: Color
) {

  let material = new SpriteMaterial({
    transparent,
    opacity,
    color: new Color(color),
    // 使用图片纹理(⚠️ 纹理不可共用 否则效果一致)
    map: getTexture()
  })
  
  // 偏移百分比
  material.map.offset = new Vector2(spriteNumber / 5, 0)
  // 分成 5 份，取其中 1 份， 占用 1/5 的大小
  material.map.repeat = new Vector2(1 / 5, 1)
  // 调整混合模式
  material.blending = AdditiveBlending

  let range = 500
  let x = Math.random() * range - range / 2
  let y = Math.random() * range - range / 2
  let z = Math.random() * range - range / 2
  
  let sprite = new Sprite(material)
  sprite.scale.set(size, size, size)
  sprite.position.set(x, y, z)
  
  return sprite
}